#!/bin/bash
# 自动构建 DEB 包 (Depends 字段终极修复版)

set -euo pipefail

# 获取项目根目录
PROJECT_ROOT=$(dirname $(realpath "$0"))/..
cd "$PROJECT_ROOT"

# 配置参数
PKG_NAME="mirror-tool"
VERSION=$(python3 -c "import core; print(core.__version__.replace('-','~'))" | cut -d+ -f1)
ARCH="amd64"
OUTPUT_DIR="build"
INSTALL_DIR="usr"

# 清理旧构建
rm -rf "${PKG_NAME}_${VERSION}"
mkdir -p "${PKG_NAME}_${VERSION}/DEBIAN"
mkdir -p "${PKG_NAME}_${VERSION}/${INSTALL_DIR}"/{bin,share/mirror-tool}

# 安装主程序（强制 UNIX 文件格式）
sed -e '1s/^/\xef\xbb\xbf/' -e '1i#!/usr/bin/env python3' core/cli.py > core/cli.tmp
install -Dm755 core/cli.tmp "${PKG_NAME}_${VERSION}/${INSTALL_DIR}/bin/mirror-tool"
rm core/cli.tmp

# 复制核心文件
find core plugins data -type f -exec dos2unix {} \;
cp -r core plugins data "${PKG_NAME}_${VERSION}/${INSTALL_DIR}/share/mirror-tool/"

# 创建严格符合 Debian Policy 的 control 文件
cat > "${PKG_NAME}_${VERSION}/DEBIAN/control" <<EOF
Package: ${PKG_NAME}
Version: ${VERSION}
Architecture: ${ARCH}
Maintainer: Mirror Tool Team <team@example.com>
Depends: 
 python3 (>= 3.6),
 python3-requests,
 python3-gnupg,
 libncursesw5 (>= 6),
 libwebkit2gtk-4.0-37 (>= 2.38.0)
Description: Linux mirror management tool
 This tool provides both CLI and TUI interfaces for managing software repositories.
 Supported distributions include Ubuntu, Debian, CentOS, and Arch Linux.
 .
 Features:
  - Automatic mirror detection
  - Speed testing
  - One-click switching
Section: utils
Priority: optional
Homepage: https://mirror-tool.example.com
EOF

# 生成 md5sums 文件
find "${PKG_NAME}_${VERSION}" -type f -exec md5sum {} + \
  | sed "s|${PKG_NAME}_${VERSION}/||" \
  > "${PKG_NAME}_${VERSION}/DEBIAN/md5sums"

# 桌面文件部署（修复分类规范）
mkdir -p "${PKG_NAME}_${VERSION}/usr/share/applications"
cp flatpak/mirror-tool.desktop "${PKG_NAME}_${VERSION}/usr/share/applications/"
sed -i '/^Categories=/s/$/GTK;/' "${PKG_NAME}_${VERSION}/usr/share/applications/mirror-tool.desktop"

# 安装后脚本（兼容所有 POSIX shell）
cat > "${PKG_NAME}_${VERSION}/DEBIAN/postinst" <<"EOF"
#!/bin/sh
set -e

# 设置重试参数
retry_max=3
retry_delay=2

# 带指数退避的 apt 更新
retry=0
until apt-get update -qq || [ $retry -eq $retry_max ]; do
    retry=$((retry+1))
    sleep $((retry_delay * 2 ** (retry-1)))
done

# 安装核心依赖（带版本锁定）
required_pkgs="
python3 (>= 3.6)
python3-requests (>= 2.25.1)
python3-gnupg (>= 0.4.7)
libncursesw5 (>= 6)
libwebkit2gtk-4.0-37 (>= 2.38.0)
"

echo "$required_pkgs" | while IFS= read -r pkg; do
    [ -z "$pkg" ] && continue
    pkg_name=$(echo "$pkg" | awk '{print $1}')
    if ! dpkg -s "$pkg_name" >/dev/null 2>&1; then
        echo "正在安装依赖: $pkg"
        apt-get install -y --no-install-recommends "$pkg_name"
    fi
done

# 更新桌面数据库（兼容所有桌面环境）
if [ -d /usr/share/applications ]; then
    which update-desktop-database >/dev/null 2>&1 && \
    update-desktop-database -q /usr/share/applications || true
fi

# 重建图标缓存（多架构支持）
for icons_dir in /usr/share/icons/*; do
    [ -d "$icons_dir" ] || continue
    which gtk-update-icon-cache >/dev/null 2>&1 && \
    gtk-update-icon-cache -qtf "$icons_dir" || true
done

# 修复文件权限（防止安全漏洞）
find /usr/share/mirror-tool -type d -exec chmod 755 {} +
find /usr/share/mirror-tool -type f -exec chmod 644 {} +
chmod 755 /usr/bin/mirror-tool
EOF
chmod 755 "${PKG_NAME}_${VERSION}/DEBIAN/postinst"

# 构建 DEB 包（强制 POSIX 格式）
fakeroot dpkg-deb -Zxz --root-owner-group --build "${PKG_NAME}_${VERSION}" "${OUTPUT_DIR}"

# 格式验证（使用最新 lintian 规则）
if command -v lintian >/dev/null 2>&1; then
    lintian --fail-on error --display-experimental --pedantic \
        "${OUTPUT_DIR}/${PKG_NAME}_${VERSION}_${ARCH}.deb" || true
fi

echo "成功构建符合 Debian Policy 4.6.1 的软件包: ${OUTPUT_DIR}/${PKG_NAME}_${VERSION}_${ARCH}.deb"